package cn.zwx.common.xxl.job;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author zhangwenxue
 */
@Configuration
@EnableConfigurationProperties(ZwxXxlJobProperties.class)
public class ZwxXxlJobConfig {

    private final Logger logger = LoggerFactory.getLogger(ZwxXxlJobConfig.class);

    @Resource
    private ZwxXxlJobProperties zwxXxlJobProperties;


    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        final ZwxXxlJobProperties.XxlJobAdmin xxlJobAdmin = zwxXxlJobProperties.getXxlJobAdmin();
        if (Objects.nonNull(xxlJobAdmin)){
            final String addresses = xxlJobAdmin.getAddresses();
            xxlJobSpringExecutor.setAdminAddresses(addresses);
        }
        final ZwxXxlJobProperties.XxlJobExecutorConf xxlJobExecutorConf = zwxXxlJobProperties.getXxlJobExecutor();
        xxlJobSpringExecutor.setAppname(xxlJobExecutorConf.getAppName());
        if (!"".equals(xxlJobExecutorConf.getAddress())){
            xxlJobSpringExecutor.setAddress(xxlJobExecutorConf.getAddress());
        }
        if (!"".equals(xxlJobExecutorConf.getIp())){
            xxlJobSpringExecutor.setIp(xxlJobExecutorConf.getIp());
        }
        if (!"".equals(xxlJobExecutorConf.getPort())){
            xxlJobSpringExecutor.setPort(Integer.parseInt(xxlJobExecutorConf.getPort()));
        }
        if (!"".equals(zwxXxlJobProperties.getAccessToken())){
            xxlJobSpringExecutor.setAccessToken(zwxXxlJobProperties.getAccessToken());
        }
        if (!"".equals(xxlJobExecutorConf.getLogPath())){
            xxlJobSpringExecutor.setLogPath(xxlJobExecutorConf.getLogPath());
        }
        xxlJobSpringExecutor.setLogRetentionDays(Integer.parseInt(xxlJobExecutorConf.getLogRetentionDays()));
        return xxlJobSpringExecutor;
    }
}
